import isPlainObject from "./utils/isPlainObject";
/**
 *
 * @param {*} reducer
 * @returns
 */
function createStore(reducer, initState, enhancer) {
  //考虑到createStore可以只传递两个参数的情况做一些判断
  console.log("weq");
  if (typeof initState === "function" && typeof enhancer === "undefined") {
    enhancer = initState;
    initState = undefined;
  }

  if (typeof enhancer !== "undefined") {
    if (typeof enhancer !== "function") {
      throw new Error(
        `Expected the enhancer to be a function. Instead, received: '${typeof enhancer}'`
      );
    }
    return enhancer(createStore)(reducer, initState);
  }

  //reducer必须是一个函数
  if (typeof reducer !== "function") {
    throw new Error("reduce must be a function");
  }
  let state; // 初始化state
  let listener = []; // 保存所有的注册函数

  if (typeof initState === "function") {
  } else {
    state = initState;
  }
  //订阅，每次调用都会返回一个取消订阅的方法
  function subscribe(callback) {
    listener.push(callback);
    return () => {
      listener = listener.filter((item) => item !== callback);
    };
  }

  //获取状态，返回当前状态
  function getState() {
    return state;
  }

  //派发动作的时候，并且触发订阅函数的执行 =>  发布订阅模式
  function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error("action必须是一个纯对象");
    }
    if (typeof action.type === "undefined") {
      throw new Error("action的type属性不能是undefined");
    }
    state = reducer(state, action);
    listener.forEach((item) => {
      item();
    });
  }
  // redux会在一开始的时候就去派发一个动作，为了初始化状态
  dispatch({ type: "@@TYEP/REDUX_INIT" });
  return {
    subscribe,
    getState,
    dispatch,
  };
}

export default createStore;
